package com.wkbb.basic.controller.open;

import com.wkbb.basic.config.BasicConfig;
import com.wkbb.basic.mapper.*;

import com.wkbb.basic.model.*;
import com.wkbb.basic.service.*;
import com.wkbb.basic.thread.BasicSynAddWeBankUserFaceTask;
import com.wkbb.basic.utils.FileUtil;
import com.wkbb.basic.utils.ImageOfbase64UtilDto;
import com.wkbb.basic.utils.WebankUtil;
import com.wkbb.basic.vo.TemporaryInfoVo;
import com.wkbb.basic.vo.WebankUserVo;
import com.wkbb.common.config.ServiceConfig;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.common.utils.ThreadPoolUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @author Alger Yang
 */
@Api(description = "微众人脸识别相关接口")
@RestController
@RequestMapping("/basic/{apiVersion}/open")
@Slf4j
public class WebankController {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private OrganizationWebankMapper organizationWebankMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebankService webankService;

    @Autowired
    private WebankUtilService webankUtilService;

    @Autowired
    private ServiceConfig serviceConfig;
    @Autowired
    private BasicConfig basicConfig;

    @Autowired
    private TemporaryInfoMapper temporaryInfoMapper;

    @Autowired
    private TemporaryLogMapper temporaryLogMapper;

    @Autowired
    private OrganizationWebankService organizationWebankService;

    @Autowired
    @Lazy
    private XmppService xmppService;

    private static String webankAppid;

    private static String webankSecret;

    private static final Integer PAGE_SIZE = 100;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @ApiOperation(value = "获取AccessToken")
    @RequestMapping(value = "/getWebankAccessToken", method = RequestMethod.GET)
    public ResultDTO<Object> getWebankAccessToken(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId
    ) {
        try {
            log.info("***********WebankController.getWebankAccessToken******apiVersion:{},orgId:{}", apiVersion, orgId);

            if (null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.getAccessToken(organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.getWebankAccessToken******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "获取SignTicket")
    @RequestMapping(value = "/getWebankSignTicket", method = RequestMethod.GET)
    public ResultDTO<Object> getWebankSignTicket(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = false) @RequestParam(value = "orgId", required = false) Long orgId,
            @ApiParam(value = "微众appid", required = false) @RequestParam(name = "weBankAppid", required = false) String weBankAppid,
            @ApiParam(value = "微众webankSecret", required = false) @RequestParam(name = "webankSecret", required = false) String webankSecret
    ) {

        try {
            log.info("***********WebankController.getWebankSignTicket******apiVersion:{},orgId:{},weBankAppid:{},webankSecret：{}", apiVersion, orgId, weBankAppid, webankSecret);


            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, weBankAppid);

            if (organizationWebank == null && StringUtil.isNotEmptyIgnoreBlank(weBankAppid)) {
                if (StringUtil.isNotEmptyIgnoreBlank(webankSecret)) {
                    //1.0平台过来额数据，在3.0里面通过weBankAppid也找不到配置，就直接用传进来的参数去获取ticket看能否获取到
                    organizationWebank = new OrganizationWebank();
                    organizationWebank.setWebankSecret(webankSecret);
                    organizationWebank.setWebankAppid(weBankAppid);
                    organizationWebank.setOrgId(orgId);
                } else {
                    return new ResultDTO<>(ErrorCode.PARAM_MISSING);
                }
            }
            if (!basicConfig.enableGetSignTicket(organizationWebank.getWebankAppid())) {
                return new ResultDTO<>(ErrorCode.COMMON_ENV_CHECK);
            }

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>( webankUtilService.getSignTicket(organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), organizationWebank.getOrgId()));
            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.getWebankSignTicket******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "添加用户组")
    @RequestMapping(value = "/addWebankGroup", method = RequestMethod.POST)
    public ResultDTO<Object> addWebankGroup(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "组编号", required = true) @RequestParam(name = "groupId", required = true) String groupId,
            @ApiParam(value = "组名称", required = true) @RequestParam(name = "groupName", required = true) String groupName,
            @ApiParam(value = "组类型 1 一般组， 2 访客组", required = true, defaultValue = "1") @RequestParam(name = "groupType", required = true) Integer groupType,
            @ApiParam(value = "备注", required = false) @RequestParam(name = "remark", required = false) String remark
    ) {

        try {
            if (StringUtil.isEmpty(groupId) || StringUtil.isEmpty(groupName) || groupType == null || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.addWebankGroup******apiVersion:{},orgId:{},groupId:{},groupName:{},groupType:{},remark:{}"
                    , apiVersion, orgId, groupId, groupName, groupType, remark);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.addGroup(groupId, groupName, groupType, remark, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.addWebankGroup******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "修改用户组")
    @RequestMapping(value = "/modifyWebankGroup", method = RequestMethod.POST)
    public ResultDTO<Object> modifyWebankGroup(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "组编号", required = true) @RequestParam(name = "groupId", required = true) String groupId,
            @ApiParam(value = "组名称", required = false) @RequestParam(name = "groupName", required = false) String groupName,
            @ApiParam(value = "组类型 1 一般组， 2 访客组", required = false) @RequestParam(name = "groupType", required = false) Integer groupType,
            @ApiParam(value = "备注", required = false) @RequestParam(name = "remark", required = false) String remark
    ) {
        try {
            if (StringUtil.isEmpty(groupId) || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.addWebankGroup******apiVersion:{},orgId:{},groupId:{},groupName:{},groupType:{},remark:{}"
                    , apiVersion, orgId, groupId, groupName, groupType, remark);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.modifyGroup(groupId, groupName, groupType, remark, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.modifyWebankGroup******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "删除用户组")
    @RequestMapping(value = "/delWebankGroup", method = RequestMethod.POST)
    public ResultDTO<Object> delWebankGroup(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "组编号", required = true) @RequestParam(name = "groupId", required = true) String groupId
    ) {
        String result;
        try {
            if (StringUtil.isEmpty(groupId) || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.delWebankGroup******apiVersion:{},orgId:{},groupId:{}", apiVersion, orgId, groupId);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.delGroup(groupId, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.delWebankGroup******", e);
            return new ResultDTO<>(false);
        }

    }

    @ApiOperation(value = "添加用户")
    @RequestMapping(value = "/addWebankPerson", method = RequestMethod.POST)
    public ResultDTO<Object> addWebankPerson(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "用户编号", required = true) @RequestParam(name = "userId", required = true) String userId,
            @ApiParam(value = "姓名", required = true) @RequestParam(name = "name", required = true) String name,
            @ApiParam(value = "设备显示名称", required = false) @RequestParam(name = "showName", required = false) String showName,
            @ApiParam(value = "证件类型 01 身份证 02 军人军官证  03 港澳回乡证  04 中国护照  07 临时身份证  08 户口薄  16 外国护照  23 港澳居民居住证  24 台湾居民居住证  99 其它个人证件", required = true, defaultValue = "99")
            @RequestParam(name = "idType", required = true) String idType,
            @ApiParam(value = "证件号", required = true, defaultValue = "999999") @RequestParam(name = "idNo", required = true) String idNo,
            @ApiParam(value = "手机号", required = false) @RequestParam(name = "phoneNo", required = false) String phoneNo,
            @ApiParam(value = "图片URL", required = false) @RequestParam(name = "photoUrl", required = false) String photoUrl
    ) {
        try {
            if (StringUtil.isEmpty(userId)
                    || StringUtil.isEmpty(name)
                    || StringUtil.isEmpty(idType)
                    || StringUtil.isEmpty(idNo) || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.addWebankPerson******apiVersion:{},orgId:{},userId:{},name:{},showName:{},idType:{}," +
                    "idNo:{},phoneNo:{},photoUrl:{}", apiVersion, orgId, userId, name, showName, idType, idNo, phoneNo, photoUrl);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.addPerson(userId, name, showName, idType, idNo, phoneNo, photoUrl, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.addWebankPerson******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "修改用户")
    @RequestMapping(value = "/modifyWebankPerson", method = RequestMethod.POST)
    public ResultDTO<Object> modifyWebankPerson(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "用户编号", required = true) @RequestParam(name = "userId", required = true) String userId,
            @ApiParam(value = "姓名", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "设备显示名称", required = false) @RequestParam(name = "showName", required = false) String showName,
            @ApiParam(value = "证件类型 01 身份证 02 军人军官证  03 港澳回乡证  04 中国护照  07 临时身份证  08 户口薄  16 外国护照  23 港澳居民居住证  24 台湾居民居住证  99 其它个人证件", required = true, defaultValue = "01")
            @RequestParam(name = "idType", required = false) String idType,
            @ApiParam(value = "证件号", required = false) @RequestParam(name = "idNo", required = false) String idNo,
            @ApiParam(value = "手机号", required = false) @RequestParam(name = "phoneNo", required = false) String phoneNo,
            @ApiParam(value = "图片URL", required = false) @RequestParam(name = "photoUrl", required = false) String photoUrl
    ) {
        try {
            if (StringUtil.isEmpty(userId) || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.modifyWebankPerson******apiVersion:{},orgId:{},userId:{},name:{},showName:{},idType:{}," +
                    "idNo:{},phoneNo:{},photoUrl:{}", apiVersion, orgId, userId, name, showName, idType, idNo, phoneNo, photoUrl);


            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.modifyPerson(userId, name, showName, idType, idNo, phoneNo, photoUrl, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.modifyWebankPerson******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "删除用户")
    @RequestMapping(value = "/delWebankPerson", method = RequestMethod.POST)
    public ResultDTO<Object> delWebankPerson(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "用户编号", required = true) @RequestParam(name = "userId", required = true) String userId
    ) {
        try {
            if (StringUtil.isEmpty(userId) || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.delWebankPerson******apiVersion:{},orgId:{},userId:{}", apiVersion, orgId, userId);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.delPerson(userId, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.delWebankPerson******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "设置人员关联组")
    @RequestMapping(value = "/setWebankGroup", method = RequestMethod.POST)
    public ResultDTO<Object> setWebankGroup(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "用户编号", required = true) @RequestParam(name = "userId", required = true) String userId,
            @ApiParam(value = "需要将人员加入的用户组列表", required = false) @RequestParam(name = "groupNo", required = false) List<Object> groupNoList
    ) {
        try {
            if (StringUtil.isEmpty(userId) || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.setWebankGroup******apiVersion:{},orgId:{},userId:{},groupNoList:{}", apiVersion, orgId, userId, groupNoList == null ? "null" : Arrays.toString(groupNoList.toArray()));

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.setGroups(userId, groupNoList, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.setWebankGroup******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "添加设备")
    @RequestMapping(value = "/addWebankDevice", method = RequestMethod.POST)
    public ResultDTO<Object> addWebankDevice(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "设备编号", required = true) @RequestParam(name = "deviceNo", required = true) String deviceNo,
            @ApiParam(value = "设备名称", required = false) @RequestParam(name = "deviceName", required = false) String deviceName,
//            @ApiParam(value = "活体验证开关 0 关闭 1 开启", required = true, defaultValue = "0") @RequestParam(name = "liveSwitch", required = true) Integer liveSwitch,
            @ApiParam(value = "摄像头类型，0:红外双目 1:单目", required = false) @RequestParam(name = "binocularOrMonocularCamera", required = false)  Integer binocularOrMonocularCamera,
            @ApiParam(value = "活体开关，0:关闭 1:开启 1) 如果摄像头类型是“红外双目”，则该开关设置的是“红外活体开关” 2) 如果摄像头类型是“1 单目”，则该开关是设置“翻拍活体开关” 3) " +
                    "如果不传值，则默认红外活体开，翻拍活体关", required = false) @RequestParam(name = "cameraTypeSwitch", required = false)   Integer cameraTypeSwitch,
            @ApiParam(value = "设备所在位置", required = false) @RequestParam(name = "location", required = false) String location,
            @ApiParam(value = "设备描述", required = false) @RequestParam(name = "remark", required = false) String remark,
            @ApiParam(value = "设备关联组列表", required = false) @RequestParam(name = "groupNoList", required = false) List<Object> groupNoList
    ) {
        try {
            if (StringUtil.isEmpty(deviceNo) || cameraTypeSwitch == null || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.addWebankDevice******apiVersion:{},orgId:{},deviceNo:{},deviceName:{},binocularOrMonocularCamera:{},cameraTypeSwitch:{},location:{}," +
                    "remark:{},groupNoList:{}", apiVersion, orgId, deviceNo, deviceName, binocularOrMonocularCamera,cameraTypeSwitch, location, remark, groupNoList);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.addDevice(deviceNo, deviceName, cameraTypeSwitch, location, remark, groupNoList, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId,binocularOrMonocularCamera,cameraTypeSwitch));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.addWebankDevice******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "添加设备")
    @RequestMapping(value = "/modifyWebankDevice", method = RequestMethod.POST)
    public ResultDTO<Object> modifyWebankDevice(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "设备编号", required = true) @RequestParam(name = "deviceNo", required = true) String deviceNo,
            @ApiParam(value = "设备名称", required = false) @RequestParam(name = "deviceName", required = false) String deviceName,
//            @ApiParam(value = "活体验证开关 0 关闭 1 开启", required = false, defaultValue = "0") @RequestParam(name = "liveSwitch", required = false) Integer liveSwitch,
            @ApiParam(value = "摄像头类型，0:红外双目 1:单目", required = false) @RequestParam(name = "binocularOrMonocularCamera", required = false)  Integer binocularOrMonocularCamera,
            @ApiParam(value = "活体开关，0:关闭 1:开启 1) 如果摄像头类型是“红外双目”，则该开关设置的是“红外活体开关” 2) 如果摄像头类型是“1 单目”，则该开关是设置“翻拍活体开关” 3) " +
                    "如果不传值，则默认红外活体开，翻拍活体关", required = false) @RequestParam(name = "cameraTypeSwitch", required = false)   Integer cameraTypeSwitch,
            @ApiParam(value = "设备所在位置", required = false) @RequestParam(name = "location", required = false) String location,
            @ApiParam(value = "设备描述", required = false) @RequestParam(name = "remark", required = false) String remark,
            @ApiParam(value = "设备状态 0 停用 1 启用", required = false) @RequestParam(name = "status", required = false) String status,
            @ApiParam(value = "重启设备是否需要初始化人脸库", required = false) @RequestParam(name = "statusSwitch", required = false) String statusSwitch,
            @ApiParam(value = "设备关联组列表", required = false) @RequestParam(name = "groupNoList", required = false) List<Object> groupNoList
    ) {
        try {
            if (StringUtil.isEmpty(deviceNo) || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.modifyWebankDevice******apiVersion:{},orgId:{},deviceNo:{},deviceName:{},binocularOrMonocularCamera:{},cameraTypeSwitch:{},location:{}," +
                    "remark:{},groupNoList:{}", apiVersion, orgId, deviceNo, deviceName, binocularOrMonocularCamera,cameraTypeSwitch, location, remark, groupNoList);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.modifyDevice(deviceNo, deviceName, cameraTypeSwitch, location, remark, status, statusSwitch, groupNoList, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId,binocularOrMonocularCamera,cameraTypeSwitch));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.modifyWebankDevice******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "删除设备")
    @RequestMapping(value = "/delWebankDevice", method = RequestMethod.POST)
    public ResultDTO<Object> delWebankDevice(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "设备编号", required = true) @RequestParam(name = "deviceNo", required = true) String deviceNo
    ) {
        try {
            if (StringUtil.isEmpty(deviceNo) || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.delWebankDevice******apiVersion:{},deviceNo:{}", apiVersion, deviceNo);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.delDevice(deviceNo, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }

            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.delWebankDevice******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "1:N 在线人脸检索")
    @RequestMapping(value = "/searchWebankFace", method = RequestMethod.POST)
    public ResultDTO<Object> searchWebankFace(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "用户编号", required = true) @RequestParam(name = "imageUrl", required = true) String imageUrl,
            @ApiParam(value = "设备编号", required = false) @RequestParam(name = "deviceNo", required = false) String deviceNo,
            @ApiParam(value = "需要将人员加入的用户组列表", required = true) @RequestParam(name = "groupNo", required = true) List<Object> groupNoList
    ) {
        try {
            if (StringUtil.isEmpty(imageUrl) || groupNoList == null || groupNoList.isEmpty() || null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.setWebankGroup******apiVersion:{},orgId:{},imageUrl:{},deviceNo:{},groupNoList:{}", apiVersion, orgId, imageUrl, deviceNo, Arrays.toString(groupNoList.toArray()));

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                return new ResultDTO<>(webankUtilService.searchFace(FileUtil.encodeImageToJpgBase64(new URL(imageUrl)), deviceNo, groupNoList, false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId));
            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.setWebankGroup******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "一键创建人脸组")
    @RequestMapping(value = "/webankSyncOrgs", method = RequestMethod.POST)
    public ResultDTO<Object> webankSyncOrgs(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId
    ) {
        try {
            log.info("***********WebankController.webankSyncOrgs******apiVersion:{},orgId:{}", apiVersion, orgId);

            if (null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            boolean lock = false;
            String lockKey = getWebankSyncOrgsRedisKey(orgId);
            int retryCount = 0;
            OrganizationWebank organizationWebank = new OrganizationWebank();
            while (!lock) {
                try {
                    lock = redisTemplateUtil.tryLock(lockKey, orgId.toString(), 120, TimeUnit.SECONDS);
                    log.info("#################准备加锁##########orgId:{}", orgId);
                } catch (Exception e) {
                    log.info("#################加锁失败..等待锁过期orgId:{}", orgId);
                    e.printStackTrace();
                }
                if (lock) {
                    log.info("----------获取当前线程名称----------ThreadName:{}" + orgId, Thread.currentThread().getName());

                    try {

                        organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

                    } catch (Exception e) {
                        log.error("-----------出错了--------", e);
                        log.info("----------获取当前线程名称----------ThreadName:{}" + orgId, Thread.currentThread().getName());
                    } finally {
                        log.info("-----------释放锁开始--------");
                        log.info("----------获取当前线程名称----------ThreadName:{}" + orgId, Thread.currentThread().getName());
                        redisTemplateUtil.releaseLock(lockKey, orgId.toString());
                        log.info("-----------释放锁结束--------lock={}", lock);
                    }
                } else {
                    try {
                        retryCount++;
                        if(retryCount>20){
                            log.info("加锁失败，重试超过20次，一键创建人脸组失败...orgId:{}" ,  orgId);
                            break;
                        }
                        log.info("等待500ms重试..." + orgId);
                        Thread.sleep(500L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }


            if (null != organizationWebank) {
                webankAppid = organizationWebank.getWebankAppid();
                webankSecret = organizationWebank.getWebankSecret();
            }

            if (null == organizationWebank) {
                OrganizationWebank newOrganizationWebank = organizationWebankService.getOrganizationWebank();

                if (null == newOrganizationWebank) {
                    return new ResultDTO<>(ErrorCode.ADD_WEBANK_CONFIG);
                }

                organizationWebank = new OrganizationWebank();
                BeanUtils.copyProperties(newOrganizationWebank, organizationWebank);

                webankAppid = newOrganizationWebank.getWebankAppid();
                webankSecret = newOrganizationWebank.getWebankSecret();
                log.info("======Webank======给此学校绑定微众配置");
                organizationWebank.setOrgId(orgId);
                organizationWebankMapper.update(organizationWebank);
                log.info("======Webank======学校绑定微众配置结束");
            }


            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                ThreadPoolUtil.addTask(() -> {
                    log.info("=========webankSyncOrgs=========开始创建人脸组");

                    log.info("=========webankSyncOrgs=========所有组织");
                    Organization organizationDto = organizationMapper.getByPrimaryKey(orgId);

                    String result = webankUtilService.addGroup(organizationDto.getId().toString(), organizationDto.getName(), 1, null, false, webankAppid, webankSecret, orgId);

                    log.info("=========webankSyncOrgs=========orgId:{},orgName:{},result:{}", organizationDto.getId(), organizationDto.getName(), result);

                    log.info("=========webankSyncOrgs=========orgId:{},orgName:{},result:{}", organizationDto.getId(), organizationDto.getName(), WebankUtil.getMessage(result));

                    log.info("=========webankSyncOrgs=========创建结束");
                });
            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.webankSyncOrgs******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "一键同步用户")
    @RequestMapping(value = "/webankSyncUsers", method = RequestMethod.POST)
    public ResultDTO<Object> webankSyncUsers(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId
    ) {
        try {
            if (null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            log.info("***********WebankController.webankSyncUsers******apiVersion:{},orgId:{},groupNoList:{}", apiVersion, orgId);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {
                ThreadPoolUtil.addTask(() -> {
                    log.info("=========webankSyncUsers=========开始同步用户");

                    List<WebankUserVo> webankUserVos = null;
                    try {
                        webankUserVos = userMapper.getWebanUserVoByOrgId(Long.parseLong(String.valueOf(orgId)));
                    } catch (NumberFormatException e) {
                        log.error("=========webankSyncUsers=========错误组织ID:{}", orgId);

                    }

                    if (webankUserVos == null || webankUserVos.isEmpty()) {
                        log.error("=========webankSyncUsers=========组织ID:{}下未找到用户", orgId);

                    }

                    //循环向
                    for (WebankUserVo webankUserVo : webankUserVos) {
                        log.info("=========webankSyncUsers=========orgId:{},user:{}", orgId, webankUserVo);
                        String result;
                        result = webankUtilService.addPerson(webankUserVo.getUserCode(), webankUserVo.getName(),
                                webankUserVo.getName(), "99", "999999", null,
                                webankUserVo.getImageUrl(), false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId);
                        log.info("=========webankSyncUsers=========addPerson,结果:{}", WebankUtil.getMessage(result));
                        if (WebankUtil.checkIfSuccess(result) || WebankUtil.userNotBindExists(result)) {

                            String setGroups = webankUtilService.setGroups(webankUserVo.getUserCode(), Arrays.asList(orgId), false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId);
                            log.info("=========webankSyncUsers=========setGroups,结果:{}", WebankUtil.getMessage(setGroups));
                        }
                    }

                    log.info("=========webankSyncUsers=========同步结束");
                });
            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.webankSyncUsers******", e);
            return new ResultDTO<>(false);
        }
    }


    @ApiOperation(value = "同步用户信息到微众(处理微众没个体没人脸)")
    @RequestMapping(value = "/addWebankUsers", method = RequestMethod.POST)
    public ResultDTO<Object> addWebankUsers(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "personId", required = true) @RequestParam(value = "personId", required = true) Long personId
    ) {
        try {
            if (null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            log.info("***********WebankController.addWebankUsers******apiVersion:{},orgId:{},personId:{}", apiVersion, orgId, personId);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                HashMap<String, Object> param = new HashMap<>();
                param.put("orgId", orgId);
                param.put("personId", personId);

                log.info("=========addWebankUsers=========开始修改用户信息");

                List<WebankUserVo> webankUserVos = null;
                try {
                    webankUserVos = userMapper.getWebanUserVoByPersonId(param);
                } catch (NumberFormatException e) {
                    log.error("=========addWebankUsers=========错误组织ID:{},错误的personId:{}", orgId, personId);

                }

                if (webankUserVos == null || webankUserVos.isEmpty()) {
                    log.error("=========addWebankUsers=========组织ID:{}下未找到用户", orgId, personId);

                }

                Boolean flag = false;
                //循环向
                for (WebankUserVo webankUserVo : webankUserVos) {
                    log.info("=========addWebankUsers=========orgId:{},user:{}", orgId, webankUserVo);
                    String result;
                    result = webankUtilService.addPerson(webankUserVo.getUserCode(), webankUserVo.getName(),
                            webankUserVo.getName(), "99", "999999", null,
                            webankUserVo.getImageUrl(), false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId);
                    log.info("=========addWebankUsers=========addPerson,结果:{}", WebankUtil.getMessage(result));

                    if (WebankUtil.checkIfSuccess(result) || WebankUtil.userNotBindExists(result)) {

                        String setGroups = webankUtilService.setGroups(webankUserVo.getUserCode(), Arrays.asList(orgId), false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId);
                        log.info("=========webankSyncUsers=========setGroups,结果:{}", WebankUtil.getMessage(setGroups));
                    }

                    if (!WebankUtil.checkIfSuccess(result)) {
                        log.info("=========新增用户信息到微众异常=========", result);
                        flag = true;
                    }
                }

                if (flag) {
                    return new ResultDTO<>(ErrorCode.ADDORMODIFYFACEERROR);
                }
                log.info("=========addWebankUsers=========新增用户信息到微众结束");

            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.addWebankUsers******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "修改用户信息到微众(处理微众有个体没人脸)")
    @RequestMapping(value = "/updateWebankUsers", method = RequestMethod.POST)
    public ResultDTO<Object> updateWebankUsers(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId,
            @ApiParam(value = "personId", required = true) @RequestParam(value = "personId", required = true) Long personId
    ) {
        String result = null;
        try {

            if (null == orgId || null == personId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            log.info("***********WebankController.updateWebankUsers******apiVersion:{},orgId:{},personId:{}", apiVersion, orgId, personId);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {

                HashMap<String, Object> param = new HashMap<>();
                param.put("orgId", orgId);
                param.put("personId", personId);

                log.info("=========updateWebankUsers=========开始修改用户信息");

                List<WebankUserVo> webankUserVos = null;
                try {
                    webankUserVos = userMapper.getWebanUserVoByPersonId(param);
                } catch (NumberFormatException e) {
                    log.error("=========updateWebankUsers=========错误组织ID:{},错误的personId:{}", orgId, personId);
                }

                if (webankUserVos == null || webankUserVos.isEmpty()) {
                    log.error("=========updateWebankUsers=========组织ID:{}下未找到用户", orgId, personId);
                }

                //循环向
                for (WebankUserVo webankUserVo : webankUserVos) {
                    log.info("=========updateWebankUsers=========orgId:{},user:{}", orgId, webankUserVo);
                    result = webankUtilService.modifyPerson(webankUserVo.getUserCode(), webankUserVo.getName(),
                            webankUserVo.getName(), "99", "999999", null,
                            webankUserVo.getImageUrl(), false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId);
                    log.info("=========updateWebankUsers=========addPerson,结果:{}", WebankUtil.getMessage(result));

                }

                if (!WebankUtil.checkIfSuccess(result)) {
                    log.info("=========修改用户信息到微众异常=========", result);
                    temporaryLogMapper.insert(TemporaryLog.builder().groupNo(webankUtilService.manageGroupList(Arrays.asList(orgId)).get(0).toString()).personId(webankUserVos.get(0).getUserCode()).status(true).webankAppid(organizationWebank.getWebankAppid()).build());
                }

                log.info("=========updateWebankUsers=========修改用户信息到微众结束");
            }
            return new ResultDTO<>(result);
        } catch (Exception e) {
            log.error("***********WebankController.updateWebankUsers******", e);
            return new ResultDTO<>(false);
        }
    }


    @ApiOperation(value = "导入微众appid")
    @PostMapping(value = "/importExcelFile")
    public ResultDTO importExcelFile(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @RequestParam("uploadFile") MultipartFile uploadFile) {
        InputStream in = null;
        try {
            if (null == uploadFile) {
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }
            if (uploadFile.isEmpty()) {
                log.error("---WebankController.importExcelFile---文件不存在！");
                return new ResultDTO(ErrorCode.BUSINESS_DATA_WRONG);
            }


            if (null != uploadFile) {
                saveWebankAppid(uploadFile);
            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("----WebankController.importExcelFile----", e);
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void saveWebankAppid(MultipartFile upfiles) {

        try {
            log.info("---------打印导入数据----------excelData:{}", upfiles);

            String fileNames = upfiles.getOriginalFilename();
            String type = fileNames.substring(fileNames.lastIndexOf(".") + 1);
            OrganizationWebank organizationWebank = new OrganizationWebank();

            Workbook wb = null;
            int a = 0;
            int b = 0;
            DecimalFormat df = new DecimalFormat("0");//格式化number String字符串

            InputStream inputStream = upfiles.getInputStream();
            try {
                if ("xls".equals(type)) {
                    wb = new HSSFWorkbook(inputStream);
                } else {
                    wb = new XSSFWorkbook(inputStream);
                }
                int lineNum = 0;
                Sheet sheet = null;
                //获取一个绝对地址的流
                //得到一个工作表
                sheet = wb.getSheetAt(0);
                //获得表头
                Row rowHead = sheet.getRow(0);
                //列数
                int rows = rowHead.getPhysicalNumberOfCells();
                //行数
                lineNum = sheet.getLastRowNum();

                for (int i = 1; i <= lineNum; i++) {
                    //获得第i行对象
                    Row row = sheet.getRow(i);
                    if (null != row.getCell(0)) {
                        organizationWebank.setWebankAppid(row.getCell(0).toString());
                    }
                    if (null != row.getCell(2)) {
                        organizationWebank.setWebankSecret(row.getCell(2).toString());
                    }

                    HashMap<String, Object> params = new HashMap<>();
                    params.put("webankAppid", row.getCell(0).toString());

                    List<OrganizationWebank> organizationWebankList = organizationWebankMapper.getListByMapParams(params);

                    if (CollectionUtils.isEmpty(organizationWebankList)) {
                        organizationWebankMapper.insert(organizationWebank);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            log.error("---------导入微众appid报错----------", e);
        }
    }

    @ApiOperation(value = "一键绑定用户组")
    @RequestMapping(value = "/setWebankSyncUsersGroup", method = RequestMethod.POST)
    public ResultDTO<Object> setWebankSyncUsersGroup(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(value = "orgId", required = true) Long orgId
    ) {
        try {
            if (null == orgId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            log.info("***********WebankController.setWebankSyncUsersGroup******apiVersion:{},orgId:{}", apiVersion, orgId);

            OrganizationWebank organizationWebank = organizationWebankService.getOrganizationWebanksByOrgId(orgId, null);

            if (null != organizationWebank && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankAppid()) && StringUtil.isNotEmptyIgnoreBlank(organizationWebank.getWebankSecret())) {
                ThreadPoolUtil.addTask(() -> {
                    log.info("=========setWebankSyncUsersGroup=========开始用户绑定分组");

                    List<WebankUserVo> webankUserVos = null;
                    try {
                        webankUserVos = userMapper.getWebanUserVoByOrgId(Long.parseLong(String.valueOf(orgId)));
                    } catch (NumberFormatException e) {
                        log.error("=========setWebankSyncUsersGroup=========错误组织ID:{}", orgId);

                    }

                    if (webankUserVos == null || webankUserVos.isEmpty()) {
                        log.error("=========setWebankSyncUsersGroup=========组织ID:{}下未找到用户", orgId);

                    }

                    //循环向
                    for (WebankUserVo webankUserVo : webankUserVos) {

                        String setGroups = webankUtilService.setGroups(webankUserVo.getUserCode(), Arrays.asList(orgId), false, organizationWebank.getWebankAppid(), organizationWebank.getWebankSecret(), orgId);
                        log.info("=========setWebankSyncUsersGroup=========setGroups,结果:{}", WebankUtil.getMessage(setGroups));

                    }

                    log.info("=========setWebankSyncUsersGroup=========用户绑定同步结束");
                });
            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.setWebankSyncUsersGroup******", e);
            return new ResultDTO<>(false);
        }
    }

    private String getWebankSyncOrgsRedisKey(Long orgId) {
        return RedisKeyConstant.WKBB_BASIC_WEBANK_DEVICE_INFO + "orgid:" + orgId;
    }


    @ApiOperation(value = "人脸录入入口")
    @RequestMapping(value = "/addWeBankUserFace", method = RequestMethod.GET)
    public ResultDTO<Object> addWeBankUserFace(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "第一张正脸照片", required = true) @RequestParam(name = "picUrlA", required = true) String picUrlA,
            @ApiParam(value = "个体ID", required = true) @RequestParam(name = "userCode", required = true) String userCode,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "集团ID", required = true) @RequestParam(name = "accountId", required = true) Long accountId,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId,
            @ApiParam(value = "1,小程序,2后台管理", required = true) @RequestParam(name = "type", required = true) Integer type,
            @ApiParam(value = "人脸相似度(相似度为整数值:范围80-99)", required = false) @RequestParam(name = "similar", required = false) Short similar
    ) {
        try {
            if (null == picUrlA || null == userCode) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.addWeBankUserFace******apiVersion:{},picUrlA:{},userCode:{},orgId:{},accountId:{},userId:{},type:{},similar:{}", apiVersion, picUrlA, userCode, orgId, accountId, userId, type, similar);

            return webankService.addWeBankUserFace(picUrlA, userCode, orgId, accountId, userId, type, similar);

        } catch (Exception e) {
            log.error("***********UtuController.addWeBankUserFace******", e);
            return new ResultDTO<>(false);
        }
    }


    @ApiOperation(value = "人脸删除")
    @RequestMapping(value = "/deleteWeBankFace", method = RequestMethod.DELETE)
    public ResultDTO<Object> deleteWeBankFace(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "个体ID", required = true) @RequestParam(name = "personId", required = true) String personId,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "删除:true,修改:false", required = true) @RequestParam(name = "isDelete", required = true) Boolean isDelete,
            @ApiParam(value = "最新人脸", required = false) @RequestParam(name = "faceUrl", required = false) String faceUrl
    ) {
        try {
            if (null == personId||null==orgId||null==isDelete||null==faceUrl) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.deleteFace******apiVersion:{},personId:{},orgId:{},flag:{},faceUrl:{}", apiVersion, personId, orgId,isDelete,faceUrl);
            String result = webankService.modifyFace(personId, orgId, isDelete, faceUrl, null, null);
            return WebankUtil.returnWebankResult(result);

        } catch (Exception e) {
            log.error("***********WebankController.deleteFace******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "一键同步微众临时表没个体没人脸用户")
    @RequestMapping(value = "/saveWebankUserInfoByTem", method = RequestMethod.POST)
    public ResultDTO<Object> saveWebankUserInfoByTem(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion
    ) {
        try {

            log.info("***********WebankController.saveWebankUserInfoByTem******apiVersion:{}", apiVersion);
            //查询所有未同步到微众的个体和人脸
            List<TemporaryInfoVo> webankUserVoByParam = temporaryInfoMapper.getWebankUserVoByParam();

            log.info("----------准备修复微众缺少个体和人脸的数据----------");
            if (CollectionUtils.isEmpty(webankUserVoByParam)) {
                log.info("----------没有可修复的数据----------");
                return new ResultDTO<>();
            }

            webankUserVoByParam.forEach((e) -> {
                log.info("=========saveWebankUserInfoByTem=========orgId:{},user:{}", e.getOrgId(), e.getUserId());
                String result;
                result = webankUtilService.addPerson(e.getPersonId(), e.getName(),
                        e.getName(), "99", "999999", null,
                        e.getHeadUrl(), false, e.getWebankAppid(), e.getWebankSecret(), e.getOrgId());
                log.info("=========saveWebankUserInfoByTem=========addPerson,结果:{}", WebankUtil.getMessage(result));

                if (WebankUtil.checkIfSuccess(result) || WebankUtil.userNotBindExists(result)) {

                    result = webankUtilService.setGroups(e.getPersonId(), Arrays.asList(e.getOrgId()), false, e.getWebankAppid(), e.getWebankSecret(), e.getOrgId());
                    log.info("=========saveWebankUserInfoByTem=========setGroups,结果:{}", WebankUtil.getMessage(result));
                }

                if (!WebankUtil.checkIfSuccess(result)) {
                    log.info("=========新增用户信息到微众异常========={}", result);
                    temporaryLogMapper.insert(TemporaryLog.builder().groupNo(webankUtilService.manageGroupList(Arrays.asList(e.getOrgId())).get(0).toString()).personId(e.getPersonId()).status(true).webankAppid(e.getWebankAppid()).build());

                } else {
                    log.info("=========新增用户信息到微众成功========={}", result);
                    temporaryLogMapper.insert(TemporaryLog.builder().groupNo(webankUtilService.manageGroupList(Arrays.asList(e.getOrgId())).get(0).toString()).personId(e.getPersonId()).status(false).webankAppid(e.getWebankAppid()).build());
                }
            });
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********WebankController.saveWebankUserInfoByTem******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "批量人脸录入")
    @RequestMapping(value = "/synAddWeBankUserFace", method = RequestMethod.GET)
    public ResultDTO<Object> synAddWeBankUserFace(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "第一张正脸照片", required = true) @RequestParam(name = "picUrlA", required = true) String picUrlA,
            @ApiParam(value = "个体ID", required = true) @RequestParam(name = "userCode", required = true) String userCode,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "集团ID", required = true) @RequestParam(name = "accountId", required = true) Long accountId,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId
    ) {
        try {
            if (null == picUrlA || null == userCode) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            log.info("***********WebankController.synAddWeBankUserFace******apiVersion:{},picUrlA:{},userCode:{},orgId:{},accountId:{},userId:{},type:{},similar:{}", apiVersion, picUrlA, userCode, orgId, accountId, userId, 1, null);

            //批量同步用户人脸
            ThreadPoolUtil.addPoolTask(new BasicSynAddWeBankUserFaceTask(webankService,picUrlA, userCode, orgId, accountId, userId));
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("***********UtuController.addWeBankUserFace******", e);
            return new ResultDTO<>(false);
        }
    }

}
